package com.woniuxy.main.util;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;

/**
 * 工具类：用来向所有客户端发送消息
 * 
 * @author Administrator
 *
 */
public class WebSocketUtil {
	
	//存放当前在聊天室中的人
	public static final Map<String, Session> SESSIONMAP = new ConcurrentHashMap<>();

	//发送数据的方法：指定向某一个客户端发送消息
	public static void sendMessage(Session session,String message){
		
		if (session!=null) {
			final RemoteEndpoint.Basic basic = session.getBasicRemote();
			if (basic!=null) {
				try {
					basic.sendText(message);	//向客户端发送消息
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	//发给所有人:	遍历map给所有人发
	public static void sendAll(String message){
		
		SESSIONMAP.forEach((sessionId,session)->sendMessage(session, message));
		
		/*Iterator<String> iterator = SESSIONMAP.keySet().iterator();
		while (iterator.hasNext()) {
			String sessionId = (String) iterator.next();
			Session session = SESSIONMAP.get(sessionId);
			sendMessage(session, message);
		}*/
	}
	
}
